package com.example.shortlink.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.shortlink.entity.ShortUrl;
import com.example.shortlink.mapper.ShortUrlMapper;
import com.example.shortlink.service.ShortUrlService;
import com.example.shortlink.util.HttpParamUtil;
import com.example.shortlink.util.NumericConvertUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;

/**
 * @author lihongmin
 * @since 2023/03/06
 **/
@Service
public class ShortUrlServiceImpl implements ShortUrlService {

    private static final String PRE_URL = "http://localhost:8080/";

    @Resource
    ShortUrlMapper mapper;

    @Resource
    HttpServletResponse response;

    /**
     * 生成短链接
     *
     * @param url 长链接
     * @return 短链接
     */
    @Override
    public String generator(String url) {
        String md5 = DigestUtils.md5DigestAsHex(url.getBytes(StandardCharsets.UTF_8));
        ShortUrl shortUrl = mapper.selectOne(Wrappers.<ShortUrl>lambdaQuery().eq(ShortUrl::getMd5, md5).last("limit 1"));
        if (Objects.isNull(shortUrl)) {
            shortUrl = new ShortUrl();
            shortUrl.setMd5(md5);
            shortUrl.setUrl(url);
            shortUrl.setPostId(IdWorker.getId());
            shortUrl.setCreatedTime(new Date());
            mapper.insert(shortUrl);
            return NumericConvertUtils.toOtherNumberSystem(shortUrl.getPostId(), 62);
        }

        String postUrl = NumericConvertUtils.toOtherNumberSystem(shortUrl.getPostId(), 62);
        return PRE_URL.concat(postUrl);

    }

    /**
     * 根据短链接重定向到原始链接
     *
     * @param url 短链接
     */
    @Override
    public ModelAndView getOriginalUrl(String url) {
        long postId = NumericConvertUtils.toDecimalNumber(url, 62);
        ShortUrl shortUrl = mapper.selectOne(Wrappers.<ShortUrl>lambdaQuery().eq(ShortUrl::getPostId, postId).last("limit 1"));
        ModelAndView view = new ModelAndView();
        // 跳转404
        if (Objects.isNull(shortUrl)) {
            view.setStatus(HttpStatus.NOT_FOUND);
            view.setViewName(StringPool.EMPTY);
        } else {
            String originalUrl = shortUrl.getUrl();
            String accessUrl = originalUrl.substring(0, originalUrl.indexOf("?"));
            view.setStatus(HttpStatus.FOUND);
            view.addAllObjects(HttpParamUtil.getParameter(originalUrl));
            view.setViewName("redirect:" + accessUrl);
        }
        return view;
    }

}
